<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document
</title>
</head>
<body>
    <script>
        function sleep(duration){
            let now = Date.now();
            while(duration+now>Date.now()){
            }
        }
        // sleep(2000);
        // console.log(123);
        // function start(){
        //     console.log(1);
        //     window.requestAnimationFrame(start);
        // }
        // window.requestAnimationFrame(start);
        let activeTimeFrame = 1000/60;
        let deadFrameTime;
        let pendingCallback;
        let channel = new MessageChannel();
        let timeRemaining = ()=>deadFrameTime - performance.now();
        channel.port2.onmessage = function(){
            console.log("接收到port1 返回的消息");
            let currentTime = performance.now();
            let didTimeOut = deadFrameTime <= currentTime;
            if(didTimeOut||timeRemaining()>0){
                if(pendingCallback){
                    pendingCallback({didTimeOut,timeRemaining})
                }
            }
        }
        window.requestIdleCallback = function(callback,option){
            window.requestAnimationFrame((rafTime)=>{
                console.log(rafTime);
                // 后面计算是否超时使用的
                deadFrameTime = rafTime + activeTimeFrame;
                pendingCallback = callback;
                channel.port1.postMessage("hello");
            })
        }
        let works = [
            ()=>{
                console.log("任务1")
                sleep(20);
            },           ()=>{
                console.log("任务2")
                sleep(20);
            },           ()=>{
                sleep(20);
                console.log("任务3")
            },           ()=>{
                sleep(20);
                console.log("任务4")
            },           ()=>{
                sleep(20);
                console.log("任务5")
            },
        ]
        function progress(dealine){
            console.log("剩下多少空闲的时间：",dealine.timeRemaining());
            if(dealine.timeRemaining()>0&&works.length>0){
                performUnitOfWork();
            }
            if(works.length>0){
                window.requestIdleCallback(progress);
            }
        }
        function performUnitOfWork(){
            let work = works.shift();
            work();
        }
        window.requestIdleCallback(progress);
    </script>
</body>
</html>